package cn.softeem.tushu.utils;

import com.alibaba.druid.pool.DruidDataSource;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class DruidPool {
    private static ThreadLocal<Connection> tl = new ThreadLocal<>();

    private static DruidDataSource pool = new DruidDataSource();

    static {
        Properties pro = new Properties();
        InputStream in = DruidPool.class.getClassLoader().getResourceAsStream("db.properties");
        try {
            pro.load(in);
            pool.setDriverClassName(pro.getProperty("driverName"));
            pool.setUrl(pro.getProperty("url"));
            pool.setUsername(pro.getProperty("user"));
            pool.setPassword(pro.getProperty("password"));
            pool.setInitialSize(Integer.valueOf(pro.getProperty("InitialSize")));
            pool.setMinIdle(Integer.valueOf(pro.getProperty("MinIdle")));
            pool.setMaxActive(Integer.valueOf(pro.getProperty("MaxActive")));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //    public static void main(String[] args) {
//        try {
//            DruidPooledConnection connection = pool.getConnection();
//            System.out.println(connection);
//        } catch (SQLException throwables) {
//            throwables.printStackTrace();
//        }
//    }
    public static Connection getConnection() throws SQLException {
        if(tl.get()==null){
            return pool.getConnection();
        }
        return tl.get();
    }

    public static void beginTransaction() throws SQLException {
        Connection connection = tl.get();
        if(connection!=null){
            throw new SQLException("已有事务");
        }
        connection = pool.getConnection();
        connection.setAutoCommit(false);
        tl.set(connection);
    }

    public static void commitTransaction() throws SQLException {
        Connection connection = tl.get();
        if(connection ==null){
            throw new SQLException("没有事务");
        }
        connection.commit();
        connection.setAutoCommit(true);
        connection.close();
        tl.remove();
    }

    public static void rollTransaction() throws SQLException {
        Connection connection = tl.get();
        if(connection ==null){
            throw new SQLException("没有事务");
        }
        connection.rollback();
        connection.setAutoCommit(true);
        connection.close();
        tl.remove();
    }

    public static void relaseConnection(Connection connection) throws SQLException {
        Connection threadCon = tl.get();
        if(threadCon == null){
            if(connection!=null){
                connection.close();
            }
        }
    }
    public static DruidDataSource getPool(){
        return pool;
    }
}
